package com.gt.quality.apim.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gt.quality.apim.domain.ApiDataInfo;
import com.gt.quality.apim.domain.ApiParamInfo;
import com.gt.quality.apim.domain.vo.ApiDataInfoByListAllVo;
import com.gt.quality.apim.domain.vo.ApiDataInfoListVo;
import com.gt.quality.apim.domain.vo.ApiDataInfoVo;
import com.gt.quality.apim.service.ApiDataInfoService;
import com.gt.quality.base.pojo.BaseLimitRequest;
import com.gt.quality.base.pojo.BaseLimitResponse;
import com.gt.quality.base.pojo.Resp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * API数据集表(ApiDataInfo)分析接口
 *
 * @author makejava
 * @since 2026-11-20 09:37:49
 */
@RestController
@RequestMapping("apiDataInfo")
@Tag(name = "apiDataInfo -RController")
@Slf4j
public class ApiDataInfoController {
    /**
     * 服务对象
     */
    private  ApiDataInfoService apiDataInfoService;

    @Autowired
    public void setApiDataInfoService(@Qualifier("apiDataInfoService") ApiDataInfoService apiDataInfoService) {
        this.apiDataInfoService = apiDataInfoService;
    }

    /**
     * 分页查询数据
     *
     * @param limitRequest 查询实体
     * @return 所有数据
     */
    @PostMapping("/queryLimit")
    @Operation(summary = "分页查询请求")
    @SaCheckPermission("decision:api:list")
    public Resp<BaseLimitResponse<ApiDataInfoListVo>> queryPage(@RequestBody BaseLimitRequest<ApiDataInfo> limitRequest) {
        // 分页查询
        IPage<ApiDataInfo> page = this.apiDataInfoService.queryLimitPage(limitRequest);
        List<ApiDataInfo> records = page.getRecords();
        List<ApiDataInfoListVo> temp = new ArrayList<>(records.size());
        if (CollUtil.isNotEmpty(records)) {
            for (ApiDataInfo recordInfo : records) {
                ApiDataInfoListVo listVo = ApiDataInfoListVo.builder().
                        id(recordInfo.getId()).
                        apiName(recordInfo.getApiName()).
                        apiCode(recordInfo.getApiCode()).
                        apiDesc(recordInfo.getApiDesc()).
                        createTime(recordInfo.getCreateTime()).build();
                temp.add(listVo);
            }
        }
        // 封装返回结果集
        BaseLimitResponse<ApiDataInfoListVo> response = new BaseLimitResponse<>();
        response.setResponseBody(temp);
        response.setPageCount(page.getPages());
        response.setTotalNum(page.getTotal());
        response.setPageSize(limitRequest.getPageSize());
        response.setPageIndex(limitRequest.getPageIndex());
        return Resp.ok(response);
    }

    /**
     * 获取全体API
     */
    @GetMapping("/listAll")
    @Operation(summary = "分页查询请求")
    public Resp<List<ApiDataInfoByListAllVo>> listAll() {
        List<ApiDataInfo> page = this.apiDataInfoService.list();
        // 过滤字段
        List<ApiDataInfoByListAllVo> list = page.stream().map(item -> new ApiDataInfoByListAllVo(item.getId(), item.getApiName(), item.getApiCode())).toList();
        // 封装返回结果集
        return Resp.ok(list);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/queryOne/{id}")
    @Operation(summary = "PathVariable路径传参-Id")
    @Parameter(name = "id", description = "id", in = ParameterIn.PATH)
    public Resp<ApiDataInfoVo> selectOne(@PathVariable("id") Serializable id) {
        return Resp.ok(this.apiDataInfoService.getByIdAndSon(id));
    }

    /**
     * 新增数据
     *
     * @param apiDataInfo 实体对象
     * @return 新增结果
     */
    @PostMapping("/save")
    @Operation(summary = "新增数据")
    @SaCheckPermission("decision:api:save")
    public Resp<String> insert(@RequestBody ApiDataInfoVo apiDataInfo) {
        String apiUrl = apiDataInfo.getApiUrl();
        if (StringUtils.isBlank(apiUrl) || (!apiUrl.startsWith("http"))) {
            return Resp.error("API地址请填写完整:http://localhost:8080/xxx");
        }
        boolean save = this.apiDataInfoService.saveApiInfoAndParam(apiDataInfo);
        String executeMsg = "新增操作,id 是：" + apiDataInfo.getId();
        return save ? Resp.ok(executeMsg) : Resp.error(executeMsg);
    }

    /**
     * 执行API测试
     *
     * @param apiDataInfo 实体对象
     * @return 新增结果
     */
    @PostMapping("/executeApi")
    @Operation(summary = "执行API测试")
    public Resp<Object> executeApi(@RequestBody ApiDataInfoVo apiDataInfo) {
        return this.apiDataInfoService.executeApi(apiDataInfo);
    }


    /**
     * 执行API测试{只需要传入参数List}
     *
     * @param apiParamInfoList 实体对象
     * @return 新增结果
     */
    @PostMapping("/executeApiByParams")
    @Operation(summary = "执行API测试")
    public Resp<Object> executeApiByParams(@RequestBody List<ApiParamInfo> apiParamInfoList) {
        return this.apiDataInfoService.executeApiByListApiParam(apiParamInfoList);
    }

    /**
     * 批量新增数据
     *
     * @param apiDataInfoList 实体对象
     * @return 新增结果
     */
    @PostMapping("/saveBatch")
    @Operation(summary = "批量新增数据")
    @SaCheckPermission("decision:api:save")
    public Resp<String> insertBatch(@RequestBody List<ApiDataInfo> apiDataInfoList) {
        Integer save = this.apiDataInfoService.saveBatchByEasyBaseMapper(apiDataInfoList);
        String executeMsg = "新增批量=>id 是：" + Arrays.toString(apiDataInfoList.stream().map(ApiDataInfo::getId).toArray());
        return save > 0 ? Resp.ok(executeMsg) : Resp.error(executeMsg);
    }


    /**
     * 修改数据
     *
     * @param apiDataInfoVo 实体对象
     * @return 修改结果
     */
    @PutMapping("/update")
    @Operation(summary = "修改数据")
    @SaCheckPermission("decision:api:update")
    public Resp<String> update(@RequestBody ApiDataInfoVo apiDataInfoVo) {
        JSONObject jsonStr = JSONUtil.parseObj(apiDataInfoVo);
        ApiDataInfo apiDataInfo = JSONUtil.toBean(jsonStr, ApiDataInfo.class);
        // 更新API主体信息
        boolean update = this.apiDataInfoService.updateById(apiDataInfo);
        // 移除原始的参数值
        apiDataInfoService.beforeDeleteParamListAndNewInsert(apiDataInfo.getId(), apiDataInfoVo.getApiParamInfoList());
        String executeMsg = "修改操作,id 是：" + apiDataInfo.getId();
        return update ? Resp.ok(executeMsg) : Resp.error(executeMsg);
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/dels")
    @Operation(summary = "删除数据-idList 主键结合")
    @SaCheckPermission("decision:api:delete")
    public Resp<String> delete(@RequestParam("idList") List<Long> idList) {
        try {
            boolean delNumber = this.apiDataInfoService.removeByIdsAndSon(idList);
            String executeMsg = "删除操作,ids 是：" + idList;
            return delNumber ?Resp.ok(executeMsg) :Resp.error(executeMsg);
        }catch (Exception e)
        {
            return Resp.error(e.getMessage());
        }
    }


}
